import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { API_CONFIG } from '../config/apiConfig';
import { useTransferStore } from './transferStore';
import router from '../router';
import { ToastService } from '../utils/toastService';

// 创建统一的会话过期处理方法
function handleSessionExpired() {
  // 清理用户数据
  localStorage.removeItem('userInfo');
  document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  
  // 使用 replace 而不是 push 来防止用户通过浏览器后退返回
  router.replace('/');
}

export interface KnowledgeFile {
  id: string;
  name: string;
  type: string;
  size: string;
  createTime: string;
}

export interface KnowledgeBaseGroup {
  id: string;
  name: string;
  open?: number; // 1表示公开，0表示保密
}

export interface KnowledgeBase {
  id: string;
  name: string;
  createTime: string;
  files: KnowledgeFile[];
  expanded: boolean;
  isFolder: boolean;
  children: KnowledgeBase[];
  parentId: string;
  level: number;
}

export const useKnowledgeBaseStore = defineStore('knowledgeBase', () => {
  // 状态
  const knowledgeBases = ref<KnowledgeBase[]>([]);
  const knowledgeBaseGroups = ref<KnowledgeBaseGroup[]>([]); // 资料库列表
  const selectedGroup = ref<KnowledgeBaseGroup | null>(null); // 当前选中的资料库
  const loadedFolders = ref<Set<string>>(new Set()); // 记录已加载的文件夹
  const selectedFolder = ref<KnowledgeBase | null>(null); // 当前选中的文件夹
  const isLoading = ref(false); // 加载状态
  const loadingMore = ref(false); // 加载更多状态
  const hasMoreFiles = ref(true); // 是否有更多文件
  const fileOffset = ref(0); // 文件加载偏移量
  const fileLimit = ref(5000); // 每次加载的文件数量

  // 获取知识库列表
  const fetchKnowledgeBases = async (parentId: string = '1', forceRefresh: boolean = false) => {
    try {
      isLoading.value = true;
      
      // 如果没有选中资料库但资料库列表不为空，使用第一个资料库
      if (!selectedGroup.value && knowledgeBaseGroups.value.length > 0) {
        selectedGroup.value = knowledgeBaseGroups.value[0];
      }
      
      // 如果已经加载过该文件夹且不是强制刷新，则不重复加载
      if (loadedFolders.value.has(parentId) && !forceRefresh) {
        isLoading.value = false;
        return;
      }

      // 添加重试机制
      let retries = 3;
      let success = false;
      let result;

      while (retries > 0 && !success) {
        try {
          const params = new URLSearchParams({
            pageNum: '1',
            pageSize: fileLimit.value.toString(),
            fatherFolderId: parentId,
            knowledgeBaseGroupId: selectedGroup.value?.id || ''
          });
          const response = await fetch(
            `${API_CONFIG.BASE_URL}/knowledge-base/page?${params.toString()}`,
            {
              credentials: 'include',
              // 添加缓存控制，避免浏览器缓存
              headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
              }
            }
          );
          
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          
          result = await response.json();
          success = true;
        } catch (e) {
          retries--;
          if (retries === 0) throw e;
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      
      if (result && result.code === '0') {
        const folders = result.data.dataList.map((item: any) => ({
          ...item,
          expanded: false,
          isFolder: true,
          children: [],
          parentId: parentId,
          level: parentId === '1' ? 0 : 1, // 根据父文件夹ID设置层级
          files: item.files || []
        }));

        // 标记该文件夹已加载
        loadedFolders.value.add(parentId);

        if (parentId === '1') {
          // 根目录，直接设置
          knowledgeBases.value = [...folders]; // 使用展开运算符创建新数组，确保响应式更新
        } else {
          // 子文件夹，更新到对应的父文件夹中
          const updateFolderChildren = (folders: KnowledgeBase[], parentId: string, newChildren: KnowledgeBase[]) => {
            for (const folder of folders) {
              if (folder.id === parentId) {
                folder.children = [...newChildren]; // 使用展开运算符创建新数组
                return true;
              }
              if (folder.children.length > 0) {
                if (updateFolderChildren(folder.children, parentId, newChildren)) {
                  return true;
                }
              }
            }
            return false;
          };
          
          updateFolderChildren(knowledgeBases.value, parentId, folders);
        }
        
        // 确保视图更新
        knowledgeBases.value = [...knowledgeBases.value];
      }else if(result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return false;
      } else {
        console.error('获取知识库列表失败:', result?.msg || '未知错误');
      }
    } catch (error) {
      console.error('获取知识库列表失败:', error);
      // 如果加载失败，从已加载文件夹集合中移除，以便下次可以重新加载
      loadedFolders.value.delete(parentId);
    } finally {
      isLoading.value = false;
    }
  };

  // 展开/折叠文件夹
  const toggleFolder = async (folder: KnowledgeBase) => {
    try {
      // 如果是展开操作，且子文件夹为空，则加载子文件夹
      if (!folder.expanded && folder.children.length === 0) {
        isLoading.value = true;
        await fetchKnowledgeBases(folder.id, true); // 强制刷新，确保获取最新数据
      }
      
      // 更新展开状态
      const updateFolderExpanded = (folders: KnowledgeBase[], targetId: string, expanded: boolean): boolean => {
        for (const f of folders) {
          if (f.id === targetId) {
            f.expanded = expanded;
            return true;
          }
          if (f.children.length > 0) {
            if (updateFolderExpanded(f.children, targetId, expanded)) {
              return true;
            }
          }
        }
        return false;
      };
      
      // 更新展开状态
      updateFolderExpanded(knowledgeBases.value, folder.id, !folder.expanded);
      // 立即设置选中的文件夹，提高UI响应速度
      // 确保视图更新
      knowledgeBases.value = [...knowledgeBases.value];
      
      // 如果展开失败，从已加载文件夹集合中移除，以便下次可以重新加载
      if (!folder.expanded && loadedFolders.value.has(folder.id)) {
        loadedFolders.value.delete(folder.id);
      }
    } catch (error) {
      console.error('切换文件夹状态失败:', error);
      // 如果加载失败，从已加载文件夹集合中移除，以便下次可以重新加载
      loadedFolders.value.delete(folder.id);
    } finally {
      isLoading.value = false;
    }
  };

  // 选择文件夹
  const selectFolder = async (folder: KnowledgeBase) => {
    // 重置分页和加载状态
    fileOffset.value = 0;
    hasMoreFiles.value = true;
    
    try {
      isLoading.value = true;
      
      // 检查folder.id是否有效
      if (!folder || !folder.id) {
        console.error('选择文件夹失败: 无效的文件夹ID', folder);
        isLoading.value = false;
        return;
      }
      
      // 1. 先加载子文件夹数据
      await fetchKnowledgeBases(folder.id, true);
      
      // 2. 从knowledgeBases中获取最新的子文件夹信息
      const currentFolder = findFolder(knowledgeBases.value, folder.id);
      if (!currentFolder) {
        console.error('找不到文件夹:', folder.id);
        return;
      }
      
      // 3. 创建深拷贝，包含最新的子文件夹信息
      const folderCopy = JSON.parse(JSON.stringify(currentFolder));
      
      // 确保文件夹对象有 files 和 children 属性
      if (!folderCopy.files) folderCopy.files = [];
      if (!folderCopy.children) folderCopy.children = [];
      
      // 4. 设置选中的文件夹，包含完整的子文件夹信息
      selectedFolder.value = folderCopy;
      
      // 5. 加载文件列表
      await fetchFolderFiles(folder.id);
    } catch (error) {
      console.error('获取文件列表失败:', error);
      // 如果选中的文件夹是当前请求的文件夹，确保它至少有一个空的文件数组
      if (selectedFolder.value && selectedFolder.value.id === folder.id) {
        selectedFolder.value.files = [];
      }
    } finally {
      isLoading.value = false;
    }
  };

  // 获取文件夹中的文件（支持滚动加载）
  const fetchFolderFiles = async (folderId: string, forceRefresh: boolean = false) => {
    try {
      isLoading.value = true;
      
      // 添加重试机制
      let retries = 3;
      let success = false;
      let result;

      while (retries > 0 && !success) {
        try {
          const params = new URLSearchParams({
            pageNum: Math.floor(fileOffset.value / fileLimit.value + 1).toString(),
            pageSize: fileLimit.value.toString(),
            knowledgeBaseId: folderId
          });

          const response = await fetch(
            `${API_CONFIG.BASE_URL}/knowledge-base/file/page?${params.toString()}`,
            {
              credentials: 'include',
              // 添加缓存控制，避免浏览器缓存
              headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
              }
            }
          );
          
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          
          result = await response.json();
          success = true;
        } catch (e) {
          retries--;
          if (retries === 0) throw e;
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      
      if (result && result.code === '0') {
        const files = (result.data.dataList || []).map((file: any) => ({
          id: file.id,
          name: file.fileName,
          size: file.fileSize,
          type: file.fileName.split('.').pop() || 'unknown',
          createTime: new Date().toISOString() // 暂时使用当前时间
        }));

        if (files.length < fileLimit.value) {
          hasMoreFiles.value = false;
        } else {
          hasMoreFiles.value = true;
        }

        // 更新选中文件夹的文件列表
        if (selectedFolder.value && selectedFolder.value.id === folderId) {
          if (fileOffset.value === 0 || forceRefresh) {
            selectedFolder.value.files = [...files]; // 使用展开运算符创建新数组
          } else {
            // 合并现有文件和新文件，确保没有重复
            const existingFileIds = new Set(selectedFolder.value.files.map((f: KnowledgeFile) => f.id));
            const uniqueNewFiles = files.filter((f: KnowledgeFile) => !existingFileIds.has(f.id));
            selectedFolder.value.files = [...selectedFolder.value.files, ...uniqueNewFiles];
          }
          
          // 同时更新knowledgeBases中对应文件夹的files
          const updateFolderFiles = (folders: KnowledgeBase[], id: string, files: KnowledgeFile[]) => {
            for (const folder of folders) {
              if (folder.id === id) {
                folder.files = [...files]; // 使用展开运算符创建新数组
                return true;
              }
              if (folder.children.length > 0) {
                if (updateFolderFiles(folder.children, id, files)) {
                  return true;
                }
              }
            }
            return false;
          };
          
          updateFolderFiles(knowledgeBases.value, folderId, selectedFolder.value.files);
          
          // 确保视图更新
          knowledgeBases.value = [...knowledgeBases.value];
        }
      } else {
        console.error('获取文件列表失败:', result?.msg || '未知错误');
      }
    } catch (error) {
      console.error('获取文件列表失败:', error);
      // 如果加载失败，确保hasMoreFiles设置为false，避免无限加载
      if (fileOffset.value > 0) {
        hasMoreFiles.value = false;
      }
    } finally {
      isLoading.value = false;
    }
  };

  // 加载更多文件
  const loadMoreFiles = async () => {
    if (!selectedFolder.value || !hasMoreFiles.value || loadingMore.value) return;
    
    try {
      loadingMore.value = true;
      fileOffset.value += fileLimit.value;
      
      // 添加重试机制
      let retries = 3;
      let success = false;
      
      while (retries > 0 && !success) {
        try {
          await fetchFolderFiles(selectedFolder.value.id);
          success = true;
        } catch (e) {
          retries--;
          if (retries === 0) throw e;
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
    } catch (error) {
      console.error('加载更多文件失败:', error);
      // 如果加载失败，恢复偏移量，避免跳过文件
      fileOffset.value -= fileLimit.value;
      // 如果连续失败多次，可以设置hasMoreFiles为false，避免无限重试
      if (fileOffset.value > 0) {
        hasMoreFiles.value = false;
      }
    } finally {
      loadingMore.value = false;
    }
  };

  // 在树中查找文件夹
  const findFolder = (folders: KnowledgeBase[], id: string): KnowledgeBase | null => {
    for (const folder of folders) {
      if (folder.id === id) {
        return folder;
      }
      if (folder.children.length > 0) {
        const found = findFolder(folder.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  // 获取知识库下的文件（兼容旧版本调用）
  const fetchFiles = async (baseId: string) => {
    const folder = findFolder(knowledgeBases.value, baseId);
    if (folder) {
      // 选择该文件夹并加载文件
      await selectFolder(folder);
    } else {
      console.error('找不到指定的文件夹:', baseId);
    }
  };

  // 创建知识库
  const createKnowledgeBase = async (name: string, fatherFolderId: string, knowledgeBaseGroupId: string): Promise<boolean> => {
    if (!name.trim()) {
      ElMessage.error('知识库名称不能为空');
      return false;
    }

    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
          name: name.trim(),
          fatherFolderId: fatherFolderId,
          knowledgeBaseGroupId: knowledgeBaseGroupId
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      if (result.code === '0') {
        // 刷新知识库列表
        await fetchKnowledgeBases(fatherFolderId, true);
        
        // 如果是在根目录创建的，刷新根目录
        if (fatherFolderId === '1') {
          await fetchKnowledgeBases('1', true);
        }
        
        ElMessage.success('创建成功');
        return true;
      } else {
        ElMessage.error(result.msg || '创建失败');
        return false;
      }
    } catch (error) {
      console.error('创建知识库失败:', error);
      ElMessage.error('创建失败，请检查网络连接');
      return false;
    }
  };

  // 删除文件
  const deleteFile = async (fileId: string) => {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/file/${fileId}/${selectedGroup.value?.id || ''}`, {
        method: 'DELETE',
        credentials: 'include'
      });
      
      const result = await response.json();
      if (result.code === '0') {
        // 如果有选中的文件夹，从其文件列表中移除文件
        if (selectedFolder.value) {
          selectedFolder.value.files = selectedFolder.value.files.filter(file => file.id !== fileId);
        }
        return true;
      } else {
        ToastService.error(result.msg || '删除失败');
        return false;
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      ToastService.error('删除失败，请检查网络连接');
      return false;
    }
  };

  // 获取文件预览URL
  const getFilePreviewUrl = (fileId: string) => {
    return `${API_CONFIG.BASE_URL}/knowledge-base/file/preview/${fileId}/${selectedGroup.value?.id || ''}`;
  };

  // 预览文件
  const previewFile = async (file: KnowledgeFile) => {
    try {
      // 根据文件类型决定预览方式
      const previewUrl = getFilePreviewUrl(file.id);
      
      // 对于图片、PDF等可以直接在浏览器中预览的文件类型
      const directPreviewTypes = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      
      if (directPreviewTypes.includes(file.type.toLowerCase())) {
        // 在新窗口中打开预览
        window.open(previewUrl, '_blank');
        return true;
      } else {
        // 对于其他类型的文件，尝试下载
        const response = await fetch(previewUrl, {
          credentials: 'include'
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 创建一个下载链接
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.name;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        return true;
      }
    } catch (error) {
      console.error('预览文件失败:', error);
      ToastService.error('预览文件失败，请检查网络连接');
      return false;
    }
  };

  // 从文件夹树中移除指定文件夹
  const removeFolderFromTree = (folders: KnowledgeBase[], id: string): boolean => {
    for (let i = 0; i < folders.length; i++) {
      if (folders[i].id === id) {
        folders.splice(i, 1);
        return true;
      }
      if (folders[i].children.length > 0) {
        if (removeFolderFromTree(folders[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  // 删除知识库
  const deleteKnowledgeBase = async (id: string) => {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/${id}/${selectedGroup.value?.id || ''}`, {
        method: 'DELETE',
        credentials: 'include'
      });

      const result = await response.json();
      if (result.code === '0') {
        // 如果删除的是当前选中的文件夹，清除选中状态
        if (selectedFolder.value?.id === id) {
          selectedFolder.value = null;
        }
        
        // 从已加载文件夹集合中移除
        loadedFolders.value.delete(id);
        
        // 从文件夹树中移除该文件夹
        removeFolderFromTree(knowledgeBases.value, id);
        
        // 确保视图更新
        knowledgeBases.value = [...knowledgeBases.value];
        return true;
      } else {
        ToastService.error(result.msg || '删除失败');
        return false;
      }
    } catch (error) {
      console.error('删除知识库失败:', error);
      ToastService.error('删除失败，请检查网络连接');
      return false;
    }
  };

  // 更新知识库信息
  const updateKnowledgeBase = async (id: string, data: { name: string; fatherFolderId: string; knowledgeBaseGroupId: string }): Promise<boolean> => {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify(data)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      if (result.code === '0') {
        // 更新本地状态
        const updateFolderName = (folders: KnowledgeBase[], id: string, newName: string) => {
          for (const folder of folders) {
            if (folder.id === id) {
              folder.name = newName;
              return true;
            }
            if (folder.children.length > 0) {
              if (updateFolderName(folder.children, id, newName)) {
                return true;
              }
            }
          }
          return false;
        };

        updateFolderName(knowledgeBases.value, id, data.name);
        
        // 如果更新的是当前选中的文件夹，也更新其名称
        if (selectedFolder.value?.id === id) {
          selectedFolder.value.name = data.name;
        }

        return true;
      } else {
        console.error('更新知识库失败:', result.msg);
        throw new Error(result.msg || '更新知识库失败');
      }
    } catch (error) {
      console.error('更新知识库失败:', error);
      throw error;
    }
  };

  // 上传文件到知识库 (单文件上传)
  const uploadFile = async (baseId: string, file: File): Promise<boolean> => {
    try {
       // 如果没有选中资料库但资料库列表不为空，使用第一个资料库
      if (!selectedGroup.value && knowledgeBaseGroups.value.length > 0) {
        selectedGroup.value = knowledgeBaseGroups.value[0];
      }
      
      // 自动显示传输列表
      const transferStore = useTransferStore();
      transferStore.showTransferList = true;
      
      const formData = new FormData();
      formData.append('file', file);
      formData.append('groupId', selectedGroup.value?.id || '');

      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/${baseId}/upload`, {
        method: 'POST',
        credentials: 'include',
        body: formData
      });

      const result = await response.json();
      if (result.code !== '0') {
        throw new Error(result.msg || '文件上传失败');
      }

      // 添加传输任务
      const taskId = result.data.taskId;
      transferStore.addTask(taskId, file.name, baseId);

      // 上传成功后刷新文件列表
      if (selectedFolder.value && selectedFolder.value.id === baseId) {
        fileOffset.value = 0;
        await fetchFolderFiles(baseId, true);
      }

      return true;
    } catch (error) {
      console.error('上传文件失败:', error);
      ToastService.error('上传失败');
      return false;
    }
  };

  // 上传文件夹到知识库（依次上传每个文件）
  const uploadDirectory = async (baseId: string, files: File[], relativePaths: string[]): Promise<boolean> => {
    try {
      // 如果没有选中资料库但资料库列表不为空，使用第一个资料库
      if (!selectedGroup.value && knowledgeBaseGroups.value.length > 0) {
        selectedGroup.value = knowledgeBaseGroups.value[0];
      }
      // 自动显示传输列表
      const transferStore = useTransferStore();
      transferStore.showTransferList = true;
      
      let successCount = 0;
      let failCount = 0;
      
      // 依次上传每个文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const relativePath = relativePaths[i];
        
        try {
          const formData = new FormData();
          formData.append('file', file);
          formData.append('path', relativePath);
          formData.append('groupId', selectedGroup.value?.id || '');
          
          const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/${baseId}/directoryUpload`, {
            method: 'POST',
            credentials: 'include',
            body: formData
          });
          
          const result = await response.json();
          if (result.code === '0') {
            successCount++;
            // 添加单独的传输任务
            const taskId = result.data.taskId;
            if (taskId) {
              // 使用文件路径作为任务名称，更直观地显示上传的是哪个文件
              const taskName = relativePath || file.name;
              transferStore.addTask(taskId, taskName, baseId);
            }
          } else {
            failCount++;
            console.error(`文件 ${file.name} 上传失败: ${result.msg}`);
            ElMessage.error(`文件 ${file.name} 上传失败: ${result.msg}`);
          }
        } catch (error) {
          failCount++;
          console.error(`文件 ${file.name} 上传失败:`, error);
          ElMessage.error(`文件 ${file.name} 上传失败`);
        }
      }
      
      // 所有文件上传完成后，显示总体结果
      if (failCount === 0 && successCount > 0) {
        ElMessage.success(`文件夹上传完成，共上传 ${successCount} 个文件`);
      } else if (failCount > 0 && successCount > 0) {
        ElMessage.warning(`文件夹上传部分完成，成功 ${successCount} 个，失败 ${failCount} 个`);
      } else if (failCount > 0 && successCount === 0) {
        ElMessage.error(`文件夹上传失败，所有 ${failCount} 个文件均上传失败`);
      } else {
        ElMessage.warning('没有文件被上传');
      }
      
      // 上传完成后刷新文件列表
      if (selectedFolder.value && selectedFolder.value.id === baseId) {
        fileOffset.value = 0;
        await fetchFolderFiles(baseId, true);
      }
      
      return failCount === 0;
    } catch (error) {
      console.error('上传文件夹失败:', error);
      ElMessage.error('上传失败，请检查网络连接');
      return false;
    }
  };

  // 初始化知识库
  const initKnowledgeBase = async (path: string, groupId: string): Promise<boolean> => {
    try {
      const params = new URLSearchParams({
        path: path,
        groupId: groupId
      });

      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base/initUpload?${params.toString()}`, {
        method: 'POST',
        credentials: 'include',
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      if (result.code === '0') {
        ElMessage.success('后台初始化中');
        return true;
      } else {
        ElMessage.error(result.msg || '初始化失败');
        return false;
      }
    } catch (error) {
      console.error('初始化知识库失败:', error);
      ElMessage.error('初始化失败，请检查网络连接');
      return false;
    }
  };

  // 获取资料库列表
  const fetchKnowledgeBaseGroups = async () => {
    try {
      isLoading.value = true;
      
      // 添加重试机制
      let retries = 3;
      let success = false;
      let result;

      while (retries > 0 && !success) {
        try {
          const params = new URLSearchParams({
            pageNum: '1',
            pageSize: '10000'
          });
          
          const response = await fetch(
            `${API_CONFIG.BASE_URL}/knowledge-base-group/page?${params.toString()}`,
            {
              credentials: 'include',
              headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
              }
            }
          );
          
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          
          result = await response.json();
          success = true;
        } catch (e) {
          retries--;
          if (retries === 0) throw e;
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      
      if (result && result.code === '0') {
        knowledgeBaseGroups.value = result.data.dataList || [];
        
        // 如果有资料库组且没有选中的资料库，自动选择第一个
        if (knowledgeBaseGroups.value.length > 0 && !selectedGroup.value) {
          selectedGroup.value = knowledgeBaseGroups.value[0];
        }
      } else if(result.code === '0001') {
        // 调用统一的会话过期处理方法
        handleSessionExpired();
        return false;
      } else {
        console.error('获取资料库列表失败:', result?.msg || '未知错误');
      }
    } catch (error) {
      console.error('获取资料库列表失败:', error);
    } finally {
      isLoading.value = false;
    }
  };

  // 创建资料库
  const createKnowledgeBaseGroup = async (name: string, open: number = 0): Promise<boolean> => {
    if (!name.trim()) {
      ElMessage.error('资料库名称不能为空');
      return false;
    }

    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base-group`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
          name: name.trim(),
          open: open
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      if (result.code === '0') {
        // 刷新资料库列表
        await fetchKnowledgeBaseGroups();
        ElMessage.success('创建成功');
        return true;
      } else {
        ElMessage.error(result.msg || '创建失败');
        return false;
      }
    } catch (error) {
      console.error('创建资料库失败:', error);
      ElMessage.error('创建失败，请检查网络连接');
      return false;
    }
  };

  // 删除资料库
  const deleteKnowledgeBaseGroup = async (groupId: string): Promise<boolean> => {
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base-group/group/${groupId}`, {
        method: 'DELETE',
        credentials: 'include'
      });

      const result = await response.json();
      if (result.code === '0') {
        // 如果删除的是当前选中的资料库，清除选中状态
        if (selectedGroup.value?.id === groupId) {
          selectedGroup.value = null;
        }
        
        // 从资料库列表中移除
        knowledgeBaseGroups.value = knowledgeBaseGroups.value.filter(group => group.id !== groupId);
        
        // 如果还有其他资料库，自动选择第一个
        if (knowledgeBaseGroups.value.length > 0 && !selectedGroup.value) {
          selectedGroup.value = knowledgeBaseGroups.value[0];
        }
        
        return true;
      } else {
        ToastService.error(result.msg || '删除失败');
        return false;
      }
    } catch (error) {
      console.error('删除资料库失败:', error);
      ToastService.error('删除失败，请检查网络连接');
      return false;
    }
  };

  // 选择资料库
  const selectGroup = async (group: KnowledgeBaseGroup) => {
    selectedGroup.value = group;
    // 选择资料库后，重置知识库列表并加载该资料库下的知识库
    knowledgeBases.value = [];
    loadedFolders.value.clear();
    selectedFolder.value = null;
    
    // 加载该资料库下的知识库
    await fetchKnowledgeBases('1', true);
  };

  return {
    knowledgeBases,
    knowledgeBaseGroups,
    selectedGroup,
    selectedFolder,
    isLoading,
    loadingMore,
    hasMoreFiles,
    loadedFolders,
    fetchKnowledgeBases,
    fetchKnowledgeBaseGroups,
    fetchFiles,
    fetchFolderFiles,
    createKnowledgeBase,
    createKnowledgeBaseGroup,
    deleteKnowledgeBase,
    deleteKnowledgeBaseGroup,
    deleteFile,
    toggleFolder,
    selectFolder,
    selectGroup,
    loadMoreFiles,
    previewFile,
    getFilePreviewUrl,
    uploadFile,
    uploadDirectory,
    updateKnowledgeBase,
    initKnowledgeBase
  };
});